package work.javac.common.database.execute;

import work.javac.bean.Partition;
import work.javac.common.Log;
import work.javac.common.database.SQLExecuteBase;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

public class OracleExecute extends SQLExecuteBase {

    StringBuffer sql = new StringBuffer();

    public Map<String, List<Partition>> getPartitions(Connection conn) throws SQLException {
        sql.setLength(0);
        sql.append(" SELECT T.TABLE_NAME, T1.PARTITION_NAME, T1.HIGH_VALUE, T2.COLUMN_NAME ");
        sql.append(" FROM USER_PART_TABLES T, USER_TAB_PARTITIONS T1, USER_PART_KEY_COLUMNS T2 ");
        sql.append(" WHERE T.TABLE_NAME = T1.TABLE_NAME ");
        sql.append(" AND T1.TABLE_NAME = T2.NAME ");
        //高斯目前只支持 范围分区
        sql.append(" AND PARTITIONING_TYPE = 'RANGE' ");
        sql.append(" ORDER BY T.TABLE_NAME, T1.PARTITION_NAME ");
        Log.info("开始查询分区信息");
        List<Map<String, Object>> dataList = executeListMap(conn, sql.toString());
        Log.info("涉及分区个数:%s", dataList.size());
        Map<String, List<Partition>> datas = new LinkedHashMap<>();
        dataList.forEach(item -> {
            String tableName = (String) item.get("TABLE_NAME");
            String partitionName = (String) item.get("PARTITION_NAME");
            String columnName = (String) item.get("COLUMN_NAME");
            String highValue = (String) item.get("HIGH_VALUE");
            int start = highValue.indexOf("'") + 1;
            int end = highValue.indexOf("'", start);
            Partition partition = new Partition();
            partition.setColumnName(columnName);
            partition.setPartitionName(partitionName);
            partition.setPartitionValueLessThan(highValue.substring(start, end).trim());
            List<Partition> partitions = datas.containsKey(tableName) ? datas.get(tableName) : new LinkedList();
            partitions.add(partition);
            datas.put(tableName, partitions);
        });
        return datas;
    }


    public String getViews(Connection conn) throws SQLException {
        sql.setLength(0);
        sql.append("SELECT TEXT,VIEW_NAME FROM USER_VIEWS");
        StringBuffer data = new StringBuffer();
        Log.info("开始查询视图信息");
        List<Map<String, Object>> dataList = executeListMap(conn, sql.toString());
        Log.info("涉及视图个数:%s", dataList.size());
        dataList.forEach(item -> {
            data.append("CREATE OR REPLACE VIEW ");
            data.append(item.get("VIEW_NAME"));
            data.append(" AS ");
            data.append(item.get("TEXT"));
            data.append(";");
            data.append("\r\n");
        });
        return data.toString();
    }
}
